<template>
  <div class="app-container home">
    <el-row :gutter="20" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sysFirstList" @selection-change="handleSelectionChange">
      <el-table-column label="首页配置项" align="center" prop="remark" />
      <!-- <el-table-column label="城市" align="center" prop="value1" />
      <el-table-column label="地区" align="center" prop="value2" />
      <el-table-column label="天气" align="center" prop="value3" />
      <el-table-column label="天气描述" align="center" prop="value4" /> -->
      <el-table-column label="首页配置值" align="center" prop="value1" />
      <!-- <el-table-column  align="center" prop="value2" />
      <el-table-column  align="center" prop="value3" /> -->
      <!-- <el-table-column  align="center" prop="value4" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sysFirst:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-table v-loading="loading" :data="sysFirstList" @selection-change="handleSelectionChange" style="margin-top: 50;">
      <el-table-column label="首页配置项" align="center" prop="remark" />
  <el-table-column label="酒店描述" align="center" prop="description">
  </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sysFirst:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    
    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改终端首页配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="城市" prop="value1">
          <el-input v-model="form.value1" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="地区" prop="value2">
          <el-input v-model="form.value2" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="天气" prop="value3">
          <el-input v-model="form.value3" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="天气描述" prop="value4">
          <el-input v-model="form.value4" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="酒店描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openCity" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="城市" prop="city">
      <el-select v-model="form.city" placeholder="请选择城市" @change="onCityChange">
        <el-option v-for="city in cities" :key="city.id" :label="city.name" :value="city.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="地区" prop="region">
      <el-select v-model="form.region" placeholder="请选择地区" :disabled="!form.city">
        <el-option v-for="region in regions" :key="region.id" :label="region.name" :value="region.name"></el-option>
      </el-select>
    </el-form-item>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :title="title" :visible.sync="openPic" width="500px" append-to-body> -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="文件上传" prop="uploadFile" required>
        <el-upload ref="field102" :file-list="field102fileList" :action="field102Action"
          :before-upload="field102BeforeUpload">
          <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
        </el-upload>
      </el-form-item> -->
      <el-input v-model="form.id" prop="id" v-if="false" />
      <el-form-item label="文件上传" prop="uploadFile" required>
      <el-upload ref="upload" :limit="1" accept=".jpg,.png, .mp4,.avi,.rmvb" 
      :headers="upload.headers" 
      :action="upload.url + '?valueId=' + form.id" 
      :disabled="upload.isUploading" 
      :on-progress="handleFileUploadProgress" 
      :on-success="handleFileSuccess" 
      :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span>支持导入图片和视频文件,仅允许jpg/png、mp4/avi/rmvb格式文件。</span>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


      <el-dialog :title="uploadBack.title" :visible.sync="uploadBack.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="背景样式" prop="value2" required>
          <el-select v-model="form.value2" style="width: 280px;">
                <el-option v-for="(item, index) in firstBackImgOrColor" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="背景颜色" prop="value3" required v-if="form.value2 == 0">
          <el-input v-model="form.value3" placeholder="请输入颜色关键字"  />
        </el-form-item>
      <el-input v-model="form.id" prop="id" v-if="false"  />
      <el-form-item label="背景图片" prop="uploadFile" required v-if="form.value2 == 1">
      <el-upload ref="uploadBack" :limit="1" accept=".jpg,.png," 
      :headers="uploadBack.headers" 
      :action="uploadBack.url + '?valueId=' + form.id" 
      :disabled="uploadBack.isUploading" 
      :on-progress="handleFileUploadBackProgress" 
      :on-success="handleFileBackSuccess" 
      :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span>支持导入图片,仅允许jpg/png格式文件。</span>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileBackForm">确 定</el-button>
        <el-button @click="uploadBack.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openDes" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="酒店描述" prop="description">
          <el-input v-model="form.description" type="textarea"  placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSysFirst, getSysFirst, delSysFirst, addSysFirst, updateSysFirst } from "@/api/system/sysFirst";
import axios from "axios";
import { getToken } from "@/utils/auth";


export default {
  name: "SysFirst",
  data() {
    return {
      // 遮罩层
      loading: true,
      getCitiesUrl: process.env.VUE_APP_BASE_API + "/system/sysFirst/getCities", // 获取所有城市
      getRegionsUrl: process.env.VUE_APP_BASE_API + "/system/sysFirst/getRegions", // 获取所有地区
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 终端首页配置表格数据
      sysFirstList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openPic: false,
      openCity: false,
      openDes: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        key: null,
        value1: null,
        value2: null,
        value3: null,
        value4: null,
        description: null,
      },
      isHotelRow:true,
      // 表单参数
      form: {
        city: '',
        region: '',
        remark: ''
      },
      // 表单校验
      rules: {
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        region: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        value3: [
          { required: true, message: '背景颜色不允许为空', trigger: "blur"}
        ]
      },
      cities: [],
      regions: [],
      // 文件导入参数
      upload: {
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/sysFirst/uploadApkFile",
      },
      //背景颜色设置
      uploadBack:{
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/sysFirst/uploadBackFile"
      },
      firstBackImgOrColor: [{
        "label": "图片",
        "value": "1"
      }, {
        "label": "颜色",
        "value": "0"
      }]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询终端首页配置列表 */
    getList() {
      this.loading = true;
      listSysFirst(this.queryParams).then(response => {
        this.sysFirstList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openCity = false;
      this.openDes = false;
      this.openPic = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keyId: null,
        value1: null,
        value2: null,
        value3: null,
        value4: null,
        description: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加终端首页配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      console.log("修改ID:"+id);
      getSysFirst(id).then(response => {
        this.form = response.data;
        // this.open = true;
        if(id == 1){
          this.openCity = true;
          this.fetchCities();
        }else if(id == 2){
          this.openDes = true;
        }else if(id == 7){
          this.uploadBack.open = true;
        }else{
          // this.openPic =true;
          this.upload.open=true;
        }

        this.title = "修改终端首页配置";
      });
    },

    async fetchCities() {
      try {
        // const response = await axios.get('/api/cities'); // 替换为实际的获取城市的接口地址
        // this.cities = response.data;
        const token = getToken();
      axios.get(this.getCitiesUrl,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.cities = response.data.data;

          console.log("获取到城市:"+JSON.stringify(this.cities));
        });
      } catch (error) {
        console.error('获取城市数据失败:', error);
      }
    },
    async onCityChange(cityValue) {
      if (cityValue) {
        this.form.region = ''; // 清空地区选择
        try {
          // const response = await axios.get(`/api/regions?city=${cityValue}`); // 替换为实际的获取地区的接口地址
          // this.regions = response.data;
          // this.form.region = ''; // 清空地区选择
          const token = getToken();
      axios.get(this.getRegionsUrl+"?city="+cityValue,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.regions = response.data.data;
          // this.form.region = ''; // 清空地区选择
        });
        } catch (error) {
          console.error('获取地区数据失败:', error);
        }
      } else {
        this.regions = [];
        this.form.region = '';
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSysFirst(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.openCity = false;
              this.openDes = false;
              this.openPic = false;
              this.uploadBack.open = false;
              this.getList();
            });
          } else {
            addSysFirst(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除终端首页配置编号为"' + ids + '"的数据项？').then(function() {
        return delSysFirst(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sysFirst/export', {
        ...this.queryParams
      }, `sysFirst_${new Date().getTime()}.xlsx`)
    },
        // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileUploadBackProgress(event, file, fileList) {
      this.uploadBack.isUploading = true;
    },
    handleFileBackSuccess(response, file, fileList) {
      this.uploadBack.open = false;
      this.uploadBack.isUploading = false;
      this.$refs.uploadBack.clearFiles();
      this.getList();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      const uploadFiles = this.$refs.upload.uploadFiles;
      console.log("当前选择上传文件个数:"+uploadFiles.length);
        if (uploadFiles.length === 0) {
          this.$message.error('请选择要上传的文件');
          return;
        }
      this.$refs.upload.submit();
    },
    submitFileBackForm() {
      console.log("点击确定按钮");
      if (this.form.value2 == 1) {
        console.log("图片");
        const uploadFiles = this.$refs.uploadBack.uploadFiles;
        console.log("文件个数:"+uploadFiles.length);
        if (uploadFiles.length === 0) {
          this.$message.error('请选择要上传背景图片');
          return;
        }
        this.$refs.uploadBack.submit();
      }else if (this.form.value2 == 0) {
        console.log("颜色");
        this.submitForm();
      }
    },
  }
};
</script>
